package com.yang;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AsyncContext
 */
@WebServlet(
		urlPatterns = { "/AsyncContext" }, 
		initParams = { 
				@WebInitParam(name = "name", value = "aa"),
				@WebInitParam(name = "word", value = "hello")
		},
		asyncSupported = true
		)
public class AsyncContextTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AsyncContextTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(final HttpServletRequest request,final HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at3: ").append(request.getContextPath());
		final AsyncContext asyncContext = request.startAsync();
		asyncContext.start(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(6000);
					System.out.println("线程结束");
					response.getWriter().append("Served at1: ").append(request.getContextPath());
					asyncContext.complete();
				} catch (InterruptedException | IOException e) {
					e.printStackTrace();
				}
			}
		});
		System.out.println("servlet end");
		response.sendRedirect("Servlet2");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
